package com.poi.batch.controller;

import com.poi.batch.domain.UserTest;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by fangjicai on 2020/6/5.
 */
@RestController
public class BatchExportController {

    @GetMapping("/batch-export")
    public void batchExport(HttpServletResponse response) throws IOException {
        //1.模拟数据
        ArrayList<UserTest> list = new ArrayList<UserTest>();
        for(int i=0;i<10;i++){
            list.add(new UserTest(i,i+"test"));
        }

        //3.构造sheet
        String[] titles = {"编号", "姓名"};
        //2.创建工作簿 设置内从中poi 对象阈值 1000
        SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(0);
        AtomicInteger headersAi = new AtomicInteger();
        for (String title : titles) {
            Cell cell = row.createCell(headersAi.getAndIncrement());
            cell.setCellValue(title);
        }
        AtomicInteger datasAi = new AtomicInteger(1);

        Cell cell = null;
        //模拟10W+数据
        for(int i=0;i<10000;i++) {
            for (UserTest report : list) {
                Row dataRow = sheet.createRow(datasAi.getAndIncrement());
                //编号
                cell = dataRow.createCell(0);
                cell.setCellValue(report.getId());
                //姓名
                cell = dataRow.createCell(1);
                cell.setCellValue(report.getName());
            }
        }
        String fileName = URLEncoder.encode("人员信息.xlsx", "UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + new
                String(fileName.getBytes("ISO8859-1")));
        response.setHeader("filename", fileName);
        workbook.write(response.getOutputStream());

    }

}
